1698C - 3SUM Closure - CodeForces Solution


brute force data structures *1300

Please click on ads to support us..

Python Code:

import sys
input = sys.stdin.readline
ii = lambda: int(input())
mi = lambda: map(int,input().split())
li = lambda: list(map(int,input().split()))
from collections import defaultdict,Counter,deque
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop,heapify

for _ in range(ii()):
    n = ii()
    nums = li()
    pos, neg = 0, 0
    for num in nums:
        if num < 0: neg += 1
        if num > 0: pos += 1
    if len(nums) < 5:
        is3sum = True
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                for k in range(j+1,len(nums)):
                    if nums[i] + nums[j] + nums[k] not in set(nums):
                        is3sum = False
        print('YES' if is3sum else 'NO')
    elif pos > 1 or neg > 1:
        print('NO')
    else:
        nums.sort()
        if pos == 1 and neg == 1 and -nums[0] != nums[-1]:
            print('NO')
        else:
            print('YES')
        

C++ Code:

#include <bits/stdc++.h>

#define ll long long
using namespace std;
const int N = 5e5 + 1;


int solve() {


    int n;
    cin >> n;
    vector<int> v;

    bool ans = 1, found_zero = 0;

    for (int i = 0; i < n; ++i) {
        int x;
        cin >> x;
        if (x != 0) {
            v.push_back(x);
        } else if (!found_zero) {
            found_zero = 1;
            v.push_back(0);
        }
    }
// -3 -2 2 0 3 -3 2 -4
    if (v.size() <= 5) {
        for (int i = 0; i < v.size(); ++i) {
            for (int j = i+1; j < v.size(); ++j) {
                for (int k = j+1; k < v.size(); ++k) {
                    if (find(v.begin(), v.end(), v[i] + v[j] + v[k]) == v.end()) {
                        ans = 0;
                    }
                }
            }
        }

    } else {
        ans = 0;
    }


    cout << (ans ? "YES" : "NO") << '\n';

    return 0;
}



int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int test_cases;
    cin >> test_cases;
    while (test_cases--) {
        solve();
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

896A - Nephren gives a riddle
761A - Dasha and Stairs
1728B - Best Permutation
1728A - Colored Balls Revisited
276B - Little Girl and Game
1181A - Chunga-Changa
1728C - Digital Logarithm
1728D - Letter Picking
792B - Counting-out Rhyme
1195A - Drinks Choosing
5D - Follow Traffic Rules
1272A - Three Friends
1632D - New Year Concert
1400D - Zigzags
716C - Plus and Square Root
412A - Poster
844B - Rectangles
1591A - Life of a Flower
1398C - Good Subarrays
629A - Far Relative’s Birthday Cake
1166A - Silent Classroom
1000B - Light It Up
218B - Airport
1463B - Find The Array
1538C - Number of Pairs
621B - Wet Shark and Bishops
476B - Dreamoon and WiFi
152C - Pocket Book
1681D - Required Length
1725D - Deducing Sortability